import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/config/app_color.dart';
import 'package:znmm/config/app_gaps.dart';
import 'package:znmm/network/notify_listener.dart';
import 'model/email_message_model.dart';
import 'view/ai_temp_view.dart';
import '../richEditor/bar_position.dart';
import '../richEditor/rich_editor.dart';
import '../richEditor/rich_editor_options.dart';
import 'mag/edti_temp_mag.dart';
import 'view/auto_temp_btn.dart';

//  ///模板编辑

class EdtiTempPage extends StatefulWidget {
  final EmailMessageModel? pModel;

  const EdtiTempPage({super.key, this.pModel});

  @override
  State<EdtiTempPage> createState() => _EdtiTempPageState();
}

class _EdtiTempPageState extends State<EdtiTempPage> {
  TextEditingController subjectController = TextEditingController();

  final GlobalKey<RichEditorState> _editorKey = GlobalKey();
  int _iNotiId1 = -1;

  String _nameText = "";
  String _subTitleText = "";

  @override
  void initState() {
    super.initState();

    if (widget.pModel != null) {
      _nameText = widget.pModel!.name!;
      _subTitleText = widget.pModel!.subject!;
      subjectController.text = widget.pModel!.subject!;
    }

    //添加监听者
    _iNotiId1 = NotifyCenter().addObserver(NotifyKey.templateEditKey, (object) {
      if (mounted) {
        setState(() {
          print("object-----:$object");

          //String simpleHtml = "<p>Hello World</p>";
          _editorKey.currentState?.setHtml(object);
        });
      }
    });
  }

  @override
  void dispose() {
    subjectController.dispose();
    EdtiTempMag().clean();
    _editorKey.currentState?.dispose();
    NotifyCenter().removeCallback(_iNotiId1);

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      ///输入框弹出时不遮挡
      // resizeToAvoidBottomInset: false,

      appBar: MyGlobal.getNavigationBar(context, '编辑模板', actions: [
        ///保存
        GestureDetector(
          onTap: () {
            _creaTemplate();
          },
          child: Padding(
            padding: EdgeInsets.only(right: 10.w),
            child: Icon(
              Icons.save,
              size: 22.w,
              color: AppColor.white,
            ),
          ),
        ),
      ]),

      body: Padding(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 15.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '名称',
              style: TextStyle(
                fontSize: 16.sp,
              ),
            ),
            TextField(
              //controller: logic.nameController,
              decoration: InputDecoration(
                hintText: '请输入名称',
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                ),
                border: InputBorder.none,
              ),
              onChanged: (value) {
                //TemplateEditMag().nameText = value;
              },
            ),
            Divider(
              height: 1,
              color: Colors.grey[300],
            ),
            Text(
              "主题",
              style: TextStyle(
                fontSize: 16.sp,
              ),
            ),
            TextField(
              controller: subjectController,
              decoration: InputDecoration(
                hintText: "请输入主题",
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                ),
                border: InputBorder.none,
              ),
              onChanged: (value) {
                //TemplateEditMag().subTitleText = value;
              },
            ),
            Divider(
              height: 1,
              color: Colors.grey[300],
            ),
            AppGaps.vGaps10w,
            Row(
              children: [
                Text(
                  '内容',
                  style: TextStyle(
                    fontSize: 16.sp,
                  ),
                ),

                ///自动生成按钮
                const AutoTempBtn(),

                //智能生成
                GestureDetector(
                  onTap: () {
                    Navigator.push(context,
                        CupertinoPageRoute(builder: (context) {
                      return const AiTempView();
                    }));
                  },
                  child: const GptTextButton(
                    text: '智能生成',
                  ),
                )
              ],
            ),
            AppGaps.vGaps10w,
            Expanded(
              child: RichEditor(
                key: _editorKey,
                //value: _stmlStr,
                value: "<p></p>", // 初始值
                getImageUrl: (file) async {
                  var result = await EdtiTempMag().onImagePickCallback(file);
                  return result;
                },
                editorOptions: RichEditorOptions(
                  placeholder: "Start typing",
                  padding: const EdgeInsets.symmetric(horizontal: 15),
                  baseFontFamily: "sans-serif",
                  barPosition: BarPosition.TOP,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _creaTemplate() async {
    if (_nameText.isEmpty) {
      MyGlobal.showInfo('请输入模板名称');
      return;
    }
    if (_subTitleText.isEmpty) {
      MyGlobal.showInfo('请输入主题');
      return;
    }
    if (_editorKey.currentState?.getHtml() == null) {
      MyGlobal.showInfo('请输入内容');
      return;
    }
    var html = await _editorKey.currentState?.getHtml();

    EdtiTempMag().createTemplate(
      _nameText,
      _subTitleText,
      html,
      callback: () {
        Get.back();
      },
    );
  }
}
